/** 
 * MemoryBar.java
 * @author Lex
 */
package org.lex.game.sudoku.util;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class MemoryBar extends JProgressBar {
	private static final long serialVersionUID = 2999826001735846981L;
	private Timer timer = null;
	private int interval = 1000;
	private boolean showPercent = true;

	public MemoryBar() {
		this(JProgressBar.HORIZONTAL);
	}

	public MemoryBar(int orient) {
		super(orient, 0, 100);
		this.setStringPainted(true);
		timer = new Timer(interval, new ActionListener() {
			StringBuilder buffer = new StringBuilder();

			public void actionPerformed(ActionEvent e) {
				Runtime rt = Runtime.getRuntime();
				long max = rt.totalMemory();
				long used = max - rt.freeMemory();
				int value = (int) (used * 100 / max);
				// ===================================
				buffer.setLength(0);
				Formatter.SizeFormat.format(used, buffer);
				buffer.append("B / ");
				Formatter.SizeFormat.format(max, buffer);
				buffer.append('B');
				if (true == showPercent) {
					buffer.append(' ').append('(');
					buffer.append(value).append('%').append(')');
				}
				setString(buffer.toString());
				setValue(value);
			}
		});
		timer.setInitialDelay(0);
		timer.start();
		this.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				Runtime.getRuntime().runFinalization();
				Runtime.getRuntime().gc();
				repaint();
			}
		});

		this.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				gc();
			}
		});
	}

	public void setShowPercent(boolean b) {
		this.showPercent = b;
		repaint();
	}

	private void gc() {
		SwingUtilities.invokeLater(new Runnable() {
			@Override
			public void run() {
				System.gc();
			}
		});
	}
}
